import React, { useState, createContext, useRef, useContext } from "react";
import EditBox from "./EditBox";

const EditBoxContext = createContext({});

function EditBoxProvider(props) {
    let [showModal, setShowModal] = useState(false);
    let [schema, setSchema] = useState({});
    let [options, setOptions] = useState({});
    let [defaultData, setDefaultData] = useState({});
    let resolveRef = useRef(null);

    const handleResult = (result) => {
        resolveRef.current(result);
        setShowModal(false);
    };

    const show = (schema, options, defaultData = {}) => {
        options.onClose = options.onClose || handleResult;
        setSchema(schema);
        setOptions(options);
        setDefaultData(defaultData);
        setShowModal(true);

        return new Promise((resolve, reject) => {
            resolveRef.current = resolve;
        });
    };

    return (
        <EditBoxContext.Provider value={show}>
            <EditBox
                schema={schema}
                options={options}
                defaultData={defaultData}
                showModal={showModal}
            />
            {props.children}
        </EditBoxContext.Provider>
    );
}

/** 
 * 以 Context 方式使用 EditBox。
 * @return {(schema: Object, options: Object, defaultData: Object) => Promise<Object>}
 */
function useEditBox() {
    return useContext(EditBoxContext);
}

export default useEditBox;
export { EditBoxProvider, EditBoxContext };
